/**
 * Created by hcadmin on 16/10/8.
 */
$(function(){
    var a         = -1;       //判断筛选 -1:全部;0:未读;1:发送人
    var filter    = false;
    var which_page="0";     //判断 1-我发送的  0-我接收的
    var teamName            = "";

    //获取url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    //debugger;
    //var localstorage = window.localStorage;
    //if (localstorage.getItem("dailyrecordDeleteFlag") != undefined){
    //    //debugger;
    //    which_page="0";
    //    localstorage.removeItem("dailyrecordDeleteFlag");
    //}


    var index = $.getUrlParam('index');
//刚进页面是的数据展示数据展示
    //----id,listType,user_id,is_read
    //initLogList("receivedContent","0",localStorage.user_id,"0");
    //initLogList("receivedContent","0",localStorage.user_id,"1");
    if(index==null||index=="1"){
        loadReceived("");
        which_page="0";
    }else{
        $("#meReceived").css("borderBottom","1px solid #e5e5e5");
        $("#meSend").css("borderBottom","0.5vw solid rgb(145,120,220)");
        $(".btn_choice").hide();
        $("#receivedContent").css("display","none");
        $("#sendContent").css("display","block");

        $(".tableview_cell_big").remove();
        loadSend();
        which_page="1";

        //initLogList("sendContent","1",user_id,"-1","",0);
    }

    function highlightById(id){
        $(id).removeClass("choice_three_cell_2");
        $(id).addClass("choice_three_cell");
    }

    function darkById(id){
        $(id).removeClass("choice_three_cell");
        $(id).addClass("choice_three_cell_2");
    }

    //点击展开筛选
    $(".btn_choice").on('click',function(){
        console.log(filter);
        console.log(a);
        if (filter == false ){
            //展开
            filter = true;
            $(".choice_div_big").show();
            $(".choice_div_big").css("display","block");
            $(".body_bgcolor").css("overflow","hidden");

            if (a == -1){
                //全部
                highlightById("#log_all");
                darkById("#log_unread");
                darkById("#log_receiver");
            }else if (a == 0){
                //未读
                darkById("#log_all");
                highlightById("#log_unread");
                darkById("#log_receiver");
            }else if (a == 1){
                //发送人
                darkById("#log_all");
                darkById("#log_unread");
                highlightById("#log_receiver");
            }
        }else {
            hideFilter();
        }







        //if(a){
            //$(".body_bgcolor").css("overflow","hidden");

        //    a=0;
        //}else{

        //
        //    a=1;
        //}

    });

    //点击内容跳转
    $(document).on('click','.tableview_cell_big',function(){

        //获取当前行的id;
        var dailyrecord_id = $(this).attr("id");
        if(which_page=="0"){
            window.location.href = "logDetail.html?index=1&id="+dailyrecord_id+"";
        }else{
            window.location.href = "logDetail.html?index=0&id="+dailyrecord_id+"";
        }
    });


    //var stop=true;//触发开关，防止多次调用事件
    //$(window).scroll(function() {
    //    //当内容滚动到底部时加载新的内容 100当距离最底部100个像素时开始加载.
    //    if ($(this).scrollTop() + $(document).height() + 4000 >= $(document).height()) {
    //
    //        if (stop == true) {
    //            stop = false;
    //            if(which_page=="0"){
    //                $(".tableview_cell_big").remove();
    //                loadReceived("")
    //            }else{
    //                $(".tableview_cell_big").remove();
    //                loadSend()
    //            }
    //        }
    //    }
    //});

    //点击"我收到的","我发出的"
    $("#meReceived").on('click',function(){
        $("#meReceived").css("color","rgb(145,120,220)").css("borderBottom","0.5vw solid rgb(145,120,220)");
        $("#meSend").css("color","black").css("borderBottom","1px solid lightgrey");
        $(".btn_choice").show();
        $("#receivedContent").css("display","block");
        $("#sendContent").css("display","none");

        $(".tableview_cell_big").remove();

        loadReceived("");
        //initLogList("receivedContent","0",user_id,"0","");
        //initLogList("receivedContent","0",user_id,"1","");

        which_page="0";
    });
    $("#meSend").on('click',function(){
        $("#meReceived").css("borderBottom","1px solid #e5e5e5");
        $("#meSend").css("borderBottom","0.5vw solid rgb(145,120,220)");
        $(".btn_choice").hide();
        $("#receivedContent").css("display","none");
        $("#sendContent").css("display","block");

        $(".tableview_cell_big").remove();
        loadSend();
        //initLogList("sendContent","1",user_id,"-1");

        which_page="1";
    });

    function loadReceived(form_id){
        //debugger;
        var id = $(".tableview_cell_big").last().attr("id")==undefined?0:$(".tableview_cell_big").first().attr("id");

        initLogList("receivedContent","0",user_id,"0",form_id,id);
        initLogList("receivedContent","0",user_id,"1",form_id,id);
    }
    function loadSend(){
        var id = $(".tableview_cell_big").last().attr("id")==undefined?0:$(".tableview_cell_big").first().attr("id");
        initLogList("sendContent","1",user_id,"-1","",id);
    }

    //隐藏筛选选项
    function hideFilter(){
        filter = false;
        $(".choice_div_big").hide();
        $(".choice_div_big").css("display","none");
        $(".body_bgcolor").css("overflow","scroll");
    }

    //点击全部
    $('#log_all').on('click',function(){

        hideFilter();
        if (a != -1){
            a = -1;
            //加载数据
            $(".tableview_cell_big").remove();
            loadReceived("");

        }
        //样式恢复

    });

    //点击 未读
    $(".un_read_choice").on('click',function(){
        //样式恢复
        $("#meReceived").css("color","rgb(145,120,220)").css("borderBottom","0.5vw solid rgb(145,120,220)");
        $("#meSend").css("color","black").css("borderBottom","1px solid lightgrey");
        $(".btn_choice").show();
        $("#receivedContent").css("display","block");
        $("#sendContent").css("display","none");
        $(".tableview_cell_big").remove();
        hideFilter();
        if (a != 0){
            //加载数据
            a = 0;
            initLogList("receivedContent","0",user_id,"0");
        }
    });

    //点击 联系人
    $(".send_person").on('click',function(){
        $(".model_div").hide();
        $(".contact_div").show();
        initpart();
    });

    getTeamName();
    //加载部门列表 已经默认成员列表
    function getTeamName(){
        var url_c  = tk_apiurl+"contacteam/findone";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'id':group_id})};
        $.ajax({
            async: false,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d) {
                var data1 = '';
                var status = '';

                data = eval('(' + d + ')');
                status = data.statusCode;
                if (data.result) {
                    data1 = eval('(' + data.result + ')');
                }

                teamName = data1.teamName;
            }
        });
    }

    function initpart(){
        var url_c  = tk_apiurl+"contacteam/mydepts";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'teamId':group_id,'parentId':"0"})};
        $.ajax({
            beforeSend:function(){
                $(".loading_c").show();
                $(".contact_bigest").hide();
            },
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){

                var data='';
                var data1='';
                var status='';

                data = eval('('+d+')');
                status = data.statusCode;
                if(data.result){
                    data1 = eval('(' + data.result + ')');
                }
                if(status==202){
                    $(".token_iframe").fadeIn(1000);
                }
                else {
                    $(".loading_c").hide();
                    //title
                    $(".contact_title").html(teamName);
                    //contact_bigest添加名称条
                    //var contact_name_html = "<div class='group_name_div'>"+localStorage.deptName+"<img src='../../approval/approvalImg/contact.png' class='group_img'></div>";
                    var contact_name_html = "<div class='group_name_div'>"+teamName+"</div>";
                    $(".contact_bigest").show().prepend(contact_name_html);
                    //$(".contact_bigest").show();
                    //加载部门
                    var team = data1.depts;
                    var html="";
                    for(var i=0;i<team.length;i++){
                        html += "<div class='team_bigest' id='"+team[i].id+"'>" +
                            "<div class='team_mid' is_choice='0'>" +
                            "<div class='team_left'>" +
                            //"<img src='../../approval/approvalImg/team.png' class='team_pic'>" +
                            "<div class='team_name'>"+team[i].departmentName+"</div>" +
                            "</div>" +
                            "<div class='team_right'>" +
                            "<img src='../../log/logImg/rightIcon.png' class='right_icon'></div></div>" +
                            "</div>";
                    }
                    $(".team_mid").each(function(){
                        $(this).last().css('borderBottom','0px');
                    });

                    //加载默认的用户
                    var users = data1.users;
                    var html_users="";

                    for(var a=0;a<users.length;a++){
                        var _choice = "0";
                        var _img    = "<img src='../../log/logImg/tick.png' class='tick_icon'>";

                        var img_url;
                        var avatar1 = users[a].avatar;
                        var qyxBindId = users[a].userIM;
                        var name = users[a].userName;

                        //if(avatar1==""){
                            var color = avatar_getColor(qyxBindId);
                            img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+name+"</div>"
                        //}else{
                        if (avatar1.length > 0) {
                            var src = avatar_getUrl(localStorage.user_id,localStorage.token,avatar1);
                            img_url += "<img src='"+src+"' class='user_pic' hidden>";
                        }

                        html_users +="<div class='user_mid' id='"+users[a].userId+"'>" +
                            "<div class='user_left'>" +
                            ""+img_url+"" +
                            "<div class='user_name'>"+users[a].userName+"</div>" +
                            "</div>" +
                            "<div class='user_right'>" +
                            ""+_img+"</div></div>";
                    }
                    $(".team_content_bigest").append(html);
                    $(".contact_content").append(html_users);
                }
                showAvatar(".user_pic");
            }
        });
    }

    //点击行获取部门下的成员列表
    var _team;
    $(document).on('click','.team_mid',function(){
        $(this).css("borderBottom","1px solid #e5e5e5");
        _team = $(this).parent();
        var is_choice = $(this).attr("is_choice");
        if(is_choice=="0") {
            $(".right_icon").addClass('right_icon_down').attr('src','../../task/images/task/arrow.png');
            var deptId = $(_team).attr("id");
            var url = tk_apiurl + "contacteam/mydeptsall";
            var data = {
                "userId": user_id,
                "token": token,
                "data": JSON.stringify({'teamId': group_id, 'deptId': deptId})
            };
            $.ajax({
                async: true,
                crossDomain: true,
                url: url,
                method: "POST",
                data: data,
                jsonpCallback: "jsoncallback",
                dataType: "jsonp",
                success: function (d) {

                    var data = '';
                    var data1 = '';
                    var status = '';

                    data = eval('(' + d + ')');
                    status = data.statusCode;
                    if (data.result) {
                        data1 = eval('(' + data.result + ')');
                    }
                    if (status == 202) {
                        $(".token_iframe").fadeIn(1000);
                    }
                    else {
                        var users = data1.users;

                        var html = "";

                        for (var i = 0; i < users.length; i++) {
                            var _choice = "0";
                            var _img = "<img src='../../log/logImg/tick.png' class='tick_icon'>";

                            //for(var j=0;j<contact_arr.length;j++){
                            //    if(contact_arr[j]==users[i].userId){
                            //        _choice = "1";
                            //        _img    = "<img src='../../log/logImg/tick.png' class='tick_icon' style='display: block'>";
                            //    }
                            //}
                            var img_url;
                            var avatar1 = users[i].avatar;
                            var qyxBindId = users[i].userIM;
                            var name = users[i].userName;
                            //if (avatar1 == "") {
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + name + "</div>"
                            //} else {
                            if (avatar1.length > 0) {
                                var src = avatar_getUrl(localStorage.user_id, localStorage.token, avatar1);
                                img_url += "<img src='" + src + "' class='user_pic' hidden>";
                            }
                            html += "<div class='user_mid' id='" + users[i].userId + "'>" +
                                "<div class='user_left'>" +
                                "" + img_url + "" +
                                "<div class='user_name'>" + users[i].userName + "</div>" +
                                "</div>" +
                                "<div class='user_right'>" +
                                "" + _img + "</div></div>";
                        }
                        $(_team).append(html);

                        $(".user_mid").last().css("border", "none");
                    }
                    showAvatar(".user_pic");
                }
            });
            $(this).attr("is_choice","1");
        }else{
            $(".right_icon").removeClass('right_icon_down').attr('src','../../log/logImg/rightIcon.png');
            $(this).nextAll().hide();
            $(this).attr("is_choice","0");
        }

    });

    //点击联系人那一行
    $(document).on('click','.user_mid',function(){
        //样式恢复
        $(".contact_div").hide();
        $(".model_div").show();
        $(".team_bigest").remove();
        $(".user_mid").remove();
        $(".group_name_div").remove();

        $("#meReceived").css("color","rgb(145,120,220)").css("borderBottom","0.5vw solid rgb(145,120,220)");
        $("#meSend").css("color","black").css("borderBottom","1px solid lightgrey");
        $(".btn_choice").show();
        $("#receivedContent").css("display","block");
        $("#sendContent").css("display","none");
        $(".tableview_cell_big").remove();

        hideFilter();
        //加载数据
        a = 1;
        var id        = $(this).attr('id');
        initLogList("receivedContent","0",user_id,"0",id,0);
        initLogList("receivedContent","0",user_id,"1",id,0);
    });

    //联系人返回
    $(".contact_back").on('click',function(){
        $(".contact_div").hide();
        $(".model_div").show();
        $(".team_bigest").remove();
        $(".user_mid").remove();
        $(".group_name_div").remove();
    });

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }

});
